<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { goodsGetFilterProducts, goodsGetCategory, goodsGetGoods, goodsHandleOfflineProducts, goodsHandleOnlineProducts, goodsDeleteProducts, fileUploadCategory } from '@/apis/apis.js'
import useGoodsStore from '@/stores/useGoodsStore.js'
import ImageUpload from '@/components/AddProduct/ImageUpload.vue'
import { emptyRegex } from '@/utils/utils.js'

const filterval = ref('')
const categoryid = ref('')
const page = ref(1)
const goodsGetFilterProductsList = ref([])
const goodsGetCategoryList = ref([])
const goodsGetGoodsList = ref([])
const total = ref(0)
const activeIndex = ref(0)
const router = useRouter()
const goodsStore = useGoodsStore()
const dialogVisible = ref(false)
const categoryName = ref('')
const imageUploadRef = ref(null)
const throttle = ref(false)

const getGoodsGetFilterProducts = async () => {
  const res = await goodsGetFilterProducts()
  goodsGetFilterProductsList.value = res.data
}

const getGoodsGetCategory = async () => {
  const res = await goodsGetCategory()
  goodsGetCategoryList.value = res.data
}

const getGoodsGetGoods = async () => {
  const res = await goodsGetGoods({ filterval: filterval.value, categoryid: categoryid.value, page: page.value })
  goodsGetGoodsList.value = res.data.res
  total.value = res.data.total
}

const formatGoodsStats = (goods_stats) => {
  return goods_stats.map(value => value.productAttributes).join('、')
}

const delist = (item) => {
  ElMessageBox.confirm(
    `确定${item.delist ? '上架' : '下架'}${item.goods_name}这个商品吗`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (item.delist) {
        await goodsHandleOnlineProducts({ goodsid: item._id })
      }
      else {
        await goodsHandleOfflineProducts({ goodsid: item._id })
      }
      getGoodsGetGoods()
    })
    .catch(() => {
    })
}

const handleDelete = (item) => {
  ElMessageBox.confirm(
    `确定删除${item.goods_name}这个商品吗？删除后将不可恢复`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await goodsDeleteProducts({ goodsid: item._id })
      await getGoodsGetCategory()
      getGoodsGetGoods()
    })
    .catch(() => {
    })
}

const toAdd = () => {
  goodsStore.updateIsEdit(false)
  goodsStore.updateCurrentGoods({})
  router.push({ name: 'AddProduct' })
}

const toEdit = (item) => {
  goodsStore.updateIsEdit(true)
  goodsStore.updateCurrentGoods(item)
  router.push({ name: 'AddProduct' })
}

const openAddCategoryDialog = () => {
  goodsStore.updateCurrentGoods({})
  goodsStore.updateIsEdit(false)
  dialogVisible.value = true
}

const addCategory = async () => {
  try {
    emptyRegex({ value: categoryName.value, msg: '分类名不能为空' })
    emptyRegex({ value: imageUploadRef.value.image, msg: '分类图标不能为空' })
    throttle.value = true
    await fileUploadCategory({ categoryName: categoryName.value, icon: imageUploadRef.value.image })
    ElMessage({ type: 'info', message: '新增分类成功', duration: 1000 })
    await getGoodsGetCategory()
    await getGoodsGetGoods()
    throttle.value = false
    dialogVisible.value = false
  }
  catch (err) {
    throttle.value = false
    console.error(err.message)
  }
}

onMounted(async () => {
  await getGoodsGetFilterProducts()
  filterval.value = goodsGetFilterProductsList.value[0].type
  await getGoodsGetCategory()
  categoryid.value = goodsGetCategoryList.value[0]._id
  await getGoodsGetGoods()

  watch([filterval, categoryid], () => {
    page.value = 1
    getGoodsGetGoods()
  })

  watch(page, () => {
    getGoodsGetGoods()
  })
})
</script>

<template>
  <el-card>
    <div style="display: flex; justify-content: flex-end; align-items: center;">
      <el-button icon="Plus" @click="openAddCategoryDialog">新建分类</el-button>
      <el-button type="warning" @click="toAdd">新建商品</el-button>
    </div>
    <el-tabs v-model="filterval">
      <el-tab-pane v-for="item in goodsGetFilterProductsList" :key="item._id" :label="item.label" :name="item.type" />
    </el-tabs>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-scrollbar style="height: 700px;">
          <div @click="activeIndex = index, categoryid = item._id" class="category-item"
            :class="{ active: index === activeIndex }"
            style="display: flex; align-items: center; padding: 20px; cursor: pointer;"
            v-for="(item, index) in goodsGetCategoryList" :key="item._id">
            <img :src="item.icon" style="width: 30px; height: 30px;">
            <span style="margin-left: 10px;">{{ item.categoryName }}({{ item.quantity }})</span>
          </div>
        </el-scrollbar>
      </el-col>
      <el-col :span="20">
        <div v-for="item in goodsGetGoodsList" :key="item._id"
          style="display: flex; justify-content: space-between; margin-bottom: 25px;">
          <div class="left" style="display: flex;">
            <img :src="item.goods_image" style="width: 100px; aspect-ratio: 1.5/1.2;">
            <div style="display: flex; flex-direction: column; justify-content: space-between; margin-left: 15px;">
              <div style="font-weight: bold;">{{ item.goods_name }}</div>
              <div>
                <span>￥{{ item.display_price }}</span>
                <span style="margin: 0 15px;">库存：{{ item.total_stock }}</span>
                <span>属性：{{ item.hasSpecs ? formatGoodsStats(item.goods_stats) : '' }}</span>
              </div>
              <div style="color: #ccc;">销量:{{ item.sales_volume }}</div>
            </div>
          </div>
          <div class="right" style="display: flex; flex-direction: column; justify-content: space-between;">
            <div class="top">
              <el-button @click="delist(item)" style="width: 100%;" :type="item.delist ? 'success' : 'info'"
                size="default">{{ item.delist ?
                  '上架' : '下架' }}</el-button>
            </div>
            <div class="bottom">
              <el-button type="success" link @click="handleDelete(item)">删除</el-button>
              <el-button type="success" link @click="toEdit(item)">编辑</el-button>
            </div>
          </div>
        </div>
        <div style="padding-top: 50px; text-align: center;" v-if="goodsGetGoodsList.length <= 0">
          <el-text type="info">无商品数据</el-text>
        </div>
        <el-pagination :hide-on-single-page="true" v-if="goodsGetGoodsList.length > 0" :page-size="10"
          v-model:current-page="page" style="--el-color-primary: orange; justify-content: center;" background
          layout="prev, pager, next" :total="total" />
      </el-col>
    </el-row>
  </el-card>
  <el-dialog v-model="dialogVisible" title="新建分类" width="500" @close="categoryName = ''">
    <el-form label-position="top" >
      <el-form-item label="填写分类名">
        <el-input placeholder="请输入分类名" v-model="categoryName" />
      </el-form-item>
      <el-form-item label="上传分类图标">
        <ImageUpload v-if="dialogVisible" ref="imageUploadRef" />
      </el-form-item>
    </el-form>
    <div style="text-align: center;">
      <el-button type="warning" size="default" @click="addCategory" :disabled="throttle">提交</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.category-item {
  &:hover {
    background-color: #f0f4f5;
  }

  &.active {
    background-color: #f0f4f5;
  }
}
</style>
